package com.zhixue.content.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.content.mapper.CourseCategoryMapper;
import com.zhixue.content.model.dto.CourseCategoryTreeDto;
import com.zhixue.content.model.po.CourseCategory;
import com.zhixue.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 李 力
 * @Date: 2025/4/7
 * @Description: com.zhixue.content.service.impl
 * @version: 1.0
 */
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper categoryMapper;

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("参数为null");
        }
        //递归查询出分类信息
        List<CourseCategoryTreeDto> treeNodes = categoryMapper.selectTreeNodes(id);
        //找到每个子节点
        Map<String, CourseCategoryTreeDto> map = treeNodes.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(CourseCategory::getId, value -> value, (key1, key2) -> key2));
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        treeNodes.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
            if (item.getParentid().equals(id)) {
                result.add(item);
            }
            CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());
            if (courseCategoryTreeDto != null) {
                if (courseCategoryTreeDto.getChildrenTreeNodes() == null) {
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<>());
                }
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });
        return result;
    }
}
